// 记录已添加商品历史
const history = new Map()
export default {
  namespaced:true,
  state:() => ({
    // 购物车的数组，用来存储购物车中每个商品的信息对象
    // 每个商品的信息对象，都包含如下 6 个属性：
    // { goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state }
    cart: JSON.parse(uni.getStorageSync('cart') || '[]')
  }),
  actions:{
    addGood({commit},good){
      const id = good.goods_id
      if(!history[id]){
        history[id] = true
        good.goods_count = 1
        commit('ADDGOOD',good)
      } else {
        commit("ADDGOODNUM",id)
      }
      
      // 更新存储数据
       commit('saveData')
    }
  },
  mutations:{
    // 添加新商品
    ADDGOOD(state,good){
      const {goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state, goods_count:count} = good
      state.cart.push({goods_id, goods_name, goods_price, goods_count, goods_small_logo, goods_state,goods_count:count})
    },
    // 添加商品数量
    ADDGOODNUM(state,id){
      const cur = state.cart.findIndex(it => it.goods_id === id)
      if(cur === -1) return
      state.cart[cur].goods_count += 1
    },
    // 删除商品
    REMOVEGOOD(state,id){
       state.cart = state.cart.filter(it => it.goods_id !== id)
       // 更新本地数据
       this.commit('cart/saveData')
    },
    // 本地存储数据
    saveData(state){
      uni.setStorageSync('cart',JSON.stringify(state.cart))
    },
    // 改变选中状态
    changeState(state,{goods_state,goods_id}){
      const cur = state.cart.findIndex(it => it.goods_id === goods_id)
      if(cur === -1) return
      state.cart[cur].goods_state = goods_state
      // 更新本地数据
      this.commit('cart/saveData')
    },
    // 改变商品数量
    changeNumber(state,{id,count}){
      const cur = state.cart.findIndex(it => it.goods_id === id)
      if(cur === -1) return
       state.cart[cur].goods_count = count
       // 更新本地数据
       this.commit('cart/saveData')
    }
  },
  getters:{
    goodsTotalNum(state){
       return state.cart.reduce((prev,it) => {
         // 根据状态的确定商品总数
         if(!it.goods_state) return prev + 0
         return prev + it.goods_count
       },0)
    },
    goodsTotalPrice(state){
      return state.cart.reduce((prev,it) => {
        // 根据状态的确定商品总数
        if(!it.goods_state) return prev + 0
        return prev + it.goods_count * it.goods_price
      },0).toFixed(2)
    }
  }
}